<template>
  <div
    class="media-mkshow"
    :class="{'fetching-box': listFetching}">
    <el-container>
      <el-main class="leftMain">
        <div class="mediaTree">
          <el-tabs style="height: 100%" v-model="activeName" type="border-card">
            <el-tab-pane :label="$t('目录管理')" name="first">
              <media-menu-tree
                :is-can-check="false"
                @currentNodeData="currentNodeDataChange"
                :api-obj="menuApiObj"
                :api-type="'3'"
              />
            </el-tab-pane>
            <el-tab-pane :label="$t('节目标签')" name="second">
              <div style="flex: 1">
                <media-tag
                  v-for="t in tagList"
                  :key="t.id"
                  :label="t.name"
                  :active="tagIds === t.id"
                  @click="handleTagClick(t)"
                />
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-main>
      <el-main class="rightMain">
        <el-tabs class="rightMain-tabs" style="height: 44px" v-model="activeName2">
          <el-tab-pane :label="$t('缩略图')" name="first"></el-tab-pane>
          <el-tab-pane :label="$t('详细信息')" name="second"></el-tab-pane>
        </el-tabs>
        <bs-main height="calc(100% - 44px)">
          <condition-row
            slot="header"
            @add="(data) => handCondition('add', data)"
            @action="(data) => handCondition('action', data)"
            @del="handCondition('del')"
            @edit="handCondition('edit')"
            @refresh="handCondition('refresh')"
            @filter="(data) => handCondition('filter', data)"
            @search="(data) => handCondition('search', data)"
          ></condition-row>
          <pagination
            slot="footer"
            :total="page.total"
            :page="page.current"
            :limit="page.size"
            :showAllChecked="true" 
            :allChecked="allSize"
            @all="handleChangeAllSize"
            @pagination="pageChange"></pagination>

          <div style="height: 100%;" v-loading="listFetching">
            <div style="margin-left: -15px;" v-show="activeName2 === 'first'">
              <mini-panel
                ref="miniPanel"
                class="center"   
                :datas="mediaData"
                @dbClick="_openPreView" />
            </div>
            <list
              height="calc( 100% - 15px )"
              ref="list"
              class="center"
              v-show="activeName2 === 'second'"
              :list-data="mediaData"
              :has-select="true"
              :list-cols="listCols"
              :init-cols-props.sync="initColsProps"
              :init-headmune-flag="initHeadmuneFlag"
              :action-opts="actionOpts"
              @sort="handleListSort"
              @editClick="handleEditClick"
              @delClick="handleDelClick"
              @init-table="initTable"
              @cell-double-click="_openPreView"
            >
              <template slot="typeSlot" slot-scope="{row}">
                {{ row.type == '1' ? $t('普通节目') : (row.type == 2 ? $t('报站节目') : $t('紧急DTMB')) }}
              </template>
              <template slot="auditStateSlot" slot-scope="{row}">
                {{ getAuditName(row.auditState) }}
              </template>
              <template slot="validitySlot" slot-scope="{row}">
                {{ row.validity ? '有效' : '无效' }}
              </template>
            </list>
          </div>
        </bs-main>
      </el-main>
    </el-container>

    <show-dialog
      :visible.sync="showDialog.show"
      :op-type="showDialog.opType"
      :form="showDialog.form"
      @addClick="addClickHandle"
      @updateClick="updateClickHandle"
      @saveClick="saveClickHandle" />

    <show-preview-dialog
    :visible.sync="previewDialog.show"
    :pre-data="previewDialog.data"
    ></show-preview-dialog>

    <examine-dialog
      :is-show-type="true"
      :visible.sync="examineDialog.show"
      @examine="handleExamine" />

  </div>
</template>

<script>
import MediaMenuTree from '../components/MediaMenuTree'
import MiniPanel from '../components/MiniPanel'
import MediaTag from '../components/MediaTag'
import List from '@/components/List'
import Pagination from '@/components/Pagination'
import ConditionRow from './components/ConditionRow'

import ShowDialog from './components/ShowDialog'
import ShowPreviewDialog from './components/ShowPreviewDialog'
import ExamineDialog from '../components/ExamineDialog'

import {genMediaMixin, MEDIA_MIXIN_CONST} from '@/mixins/mediaMixins.js'

import MediaApi from '@/api/media'

import { createNamespacedHelpers } from 'vuex'
const {mapGetters, mapActions} = createNamespacedHelpers('media')
import {programTypeOpts} from './const'

export default {
  mixins: [genMediaMixin(MEDIA_MIXIN_CONST.TYPE_MEDIA_MKSHOW)],
  filters: {
    getTypeName(v) {
      let fileType = programTypeOpts.find(item => item.value == v)
      return fileType ? fileType.label : '节目'
    }
  },
  components: {
    MediaMenuTree,
    MiniPanel,
    MediaTag,
    List,
    Pagination,
    ConditionRow,
    ShowDialog,
    ShowPreviewDialog,
    ExamineDialog
  },
  name: 'media-mkshow',
  data() {
    const headerContextMenus = {
      width: '120px',
      items: [
        'sortUp',
        'sortDown',
        'line',
        'cols'
      ]
    }

    return {
      actionOpts: {
        show: true,
        align: 'center',
        width: '120px',
        name: '操作'
      },
      menuApiObj: {
        get: MediaApi.getCatalogue,
        add: MediaApi.saveCatalogue,
        update: MediaApi.updateCatalogue,
        del: MediaApi.delCatalogue,
        bottomGet: MediaApi.getFollow,
        getOtherMedia: MediaApi.getOtherMedia
      },
      programForm: {
        "argus": "",
        "folderId": 0,
        "name": "",
        "programMedia": [],
        "tagList": [],
        "templateId": 0
      },
      examineDialog: {
        show: false
      },
      previewDialog: {
        show: false
      },
      showDialog: {
        show: false
      },
      activeName: 'first',
      activeName2: 'first',
      treeLoading: false,
      treeData: [],
      defaultCheckedKeys: [],
      contextMenuData: [],
      mediaData: [],
      listCols: [
        {label: '名称', prop: 'name', headerContextMenus, minwidth: 80},
        {label: '类型', prop: 'type', headerContextMenus, minwidth: 80, slot: true},
        {label: '审核', prop: 'auditState', headerContextMenus, minwidth: 80, slot: true},
        {label: '被使用', prop: 'refCount', headerContextMenus, minwidth: 100},
        {label: '有效性', prop: 'validity', headerContextMenus, minwidth: 100, slot: true},
        {label: '修订号', prop: 'revision', headerContextMenus, minwidth: 100},
        {label: '创建时间', prop: 'createdAt', headerContextMenus, minwidth: 100},
      ],
      initColsProps: ['name', 'type', 'auditState', 'refCount', 'validity', 'revision', 'createdAt'],
      page: {
        current: 1,
        size: 15,
        total: 0
      },
      folderId: 0,
      search: {
        queryType: 0,
        queryParam: ''
      },
      sort: {
        orderType: '',
        ordersParam: ''
      },
      sortFieldMap: {
        'name': 1,
        'type': 2,
        'auditState': 3,
        'refCount': 4,
        'validity': 5,
        'revision': 6,
        'createdAt': 7
      },
      filterAuditState: '', // 状态过滤值
      tagIds: '',
      tableName:'programListTable',
      initHeadmuneFlag: false,
      allSize: false
    }
  },
  computed: {
    ...mapGetters(['tagList', 'needFetchingList']),
    needFetching() {
      return this.needFetchingList('program')
    },
  },
  watch: {
    activeName(v) {
      if (v === 'second') {
        this.getTagList()
      } else {
        this.tagIds = ''
      }
    },
    needFetching(v) {
      if (v) {
        if (this.activeName === 'second') { // 当前正在标签页
          this.tagIds && this.fetchList() // 且已选标签才刷新请求
        } else { // 在目录树页
          const noReqId = [-1, -2] // 不做请求的目录ID
          noReqId.indexOf(this.folderId) === -1 && this.fetchList()
        }   
        this.clearNeedFetcing({change: 'program'})
      }
    }
  },
  created () {
    this.pageChange({page: this.page.current, limit: this.page.size})
    this.getTagList()
    if (!this.$_has('MEDIA_PROGRAM_UPDATE') && !this.$_has('MEDIA_PROGRAM_DELETE')) {
      this.actionOpts = {
        show: false
      }
    } else {
      this.actionOpts = {
        ...this.actionOpts,
        hidEditBtn: !this.$_has('MEDIA_PROGRAM_UPDATE'),
        hidDelBtn: !this.$_has('MEDIA_PROGRAM_DELETE')
      }
    }
  },
  methods: {
    getAuditName(v) {
      const map = {
        '-3': '待三级审核',
        '-2': '待二级审核',
        '-1': '已拒绝',
        '0': '待审核',
        '1': '已通过'
      }
      return map[v] ? this.$t(map[v]) : v
    },
    ...mapActions(['getTagList', 'getTagTree', 'clearNeedFetcing', 'setNeedFetching']),
    handleListSort({type, prop}) {
      if (this.sortFieldMap[prop]) {
        this.sort = {
          orderType: this.sortFieldMap[prop],
          ordersParam: type.toLowerCase()
        }
        this.fetchList()
      }
    },
    handleTagClick(t) {
      this.tagIds = t.id
      this.page.current = 1
      this.fetchList()
      console.log('tag按下', t)
    },
    handleEditClick(row) {
      if (this._isSubOrOther()) return
      this._openEditView(row)
      console.log('edit', row)
    },
    handleDelClick(row) {
      if (this._isSubOrOther()) return
      this._handleDel(row)
      console.log('del', row)
    },
    getActiveItem() {
      if (this.activeName2 === 'first') {
        return this.$refs.miniPanel.getActiveItem()
      } else {
        let items = this.$refs.list.getActiveItem()
        return items.length === 1 ? items[0] : items.length === 0 ? null : items
      }
    },
    _isSubOrOther() {
      if (this.folderId === -1 || this.folderId === -2 || this.isOtherMenu) {
        this.$alert('提示', '此目录不可操作')
        return true
      }
      return false
    },
    handCondition(type, data) {
      switch(type) {
        case 'add':
          if (this._isSubOrOther()) return
          this._openAddView()
          break;
        case 'action':
          this._handleAction(data)
          break;
        case 'del':
          if (this._isSubOrOther()) return
          this._handleDel(
            this.getActiveItem()
          )
          break;
        case 'edit':
          if (this._isSubOrOther()) return
          this._openEditView(this.getActiveItem())
          break;
        case 'filter':
          this._handleFilter(data)
          break;
        case 'refresh':
          this._handleRefresh()
          break;
        case 'search': 
          this._handleSearch(data)
          break;
        default: console.log('未知操作');
      }
    },
    _openAddView() {
      this.getTagTree(this.getTagTree(this.search.ownerUserId ? {
        ownerUserIds: [this.search.ownerUserId]
      } : {_self: true}))
      const programFormCopy = JSON.parse(JSON.stringify(this.programForm))
      this.showDialog = {
        ...this.showDialog,
        show: true,
        opType: '1',
        form: {
          ...programFormCopy,
          folderId: this.folderId
        }
      }
    },
    async getProgramInfo(id, cb) {
      const res = await MediaApi.getProgramInfo({id})
      cb && cb(res)
    },
    _openEditView(file) {
      if (!file) return this.$alert('提示', '请选择节目')
      if (file instanceof Array) return this.$alert('提示', '此操作不支持多选')
      this.getTagTree(this.getTagTree(this.search.ownerUserId ? {
        ownerUserIds: [this.search.ownerUserId]
      } : {_self: true}))

      this.getProgramInfo(file.id, (info) => {
        const copyFile = JSON.parse(JSON.stringify(file))
        this.showDialog = {
          ...this.showDialog,
          show: true,
          opType: '2',
          form: {
            ...copyFile,
            ...info
          }
        }
      })

    },
    _openSave(file) {
      if (!file) return this.$alert('提示', '请选择节目')
      if (file instanceof Array) return this.$alert('提示', '此操作不支持多选')
      this.getTagTree(this.getTagTree(this.search.ownerUserId ? {
        ownerUserIds: [this.search.ownerUserId]
      } : {_self: true}))

      this.getProgramInfo(file.id, (info) => {
        const copyFile = JSON.parse(JSON.stringify(file))
        let newName = copyFile.name + '2'
        // let spname = copyFile.name.split('_')
        // let lastNum = Number(spname[spname.length - 1])
        // if (!isNaN(lastNum)) {
        //   lastNum++
        //   spname[spname.length -1] = lastNum
        //   newName = spname.join('_')
        // } else {
        //   newName = copyFile.name + '2'
        // }

        this.showDialog = {
          ...this.showDialog,
          show: true,
          opType: '3',
          form: {
            ...copyFile,
            ...info,
            name: newName,
            folderId: this.folderId,
          }
        }
      })

    },
    async _handleDel(file) {
      if (!this.allSize && !file) {
        this.$alert('提示', '请选择节目')
        return
      }
      this.$confirm('提示', '是否确定删除？').then(bool => {
        let queryData = {}
        if(this.allSize) {
          queryData = {
            ...this.search,
            total: this.page.total,
            allSize: this.allSize
          }
          if(this.activeName === 'first') {
            queryData.folderId = this.folderId
          } else {
            queryData.tagId = this.tagIds
            delete queryData.ownerUserId
          }
        }
        bool && this.delMedia(file, queryData)
      })
    },
    _handleAction(type) {
      switch(type) {
        case '预览':
          this._openPreView(
            this.getActiveItem()
          )
          break;
        case '审核':
          if (this._isSubOrOther()) return
          this._openCheck(
            this.getActiveItem()
          )
          break;
        case '另存为':
          if (this._isSubOrOther()) return
          this._openSave(
            this.getActiveItem()
          )
          break;
        default:
      }
    },
    // 判断是否有已审核过的文件
    _isSomeChecked(file) {
      const canCheck = [-2, -3, 0]
      if (file instanceof Array) {
        return file.some(item => canCheck.indexOf(item.auditState) === -1)
      } else {
        return canCheck.indexOf(file.auditState) === -1
      }
    },
    _openCheck(file) {
      if(!this.allSize) {
        if (!file) return this.$alert('提示', '请选择节目')
        if (this._isSomeChecked(file)) return this.$alert('提示', '已审核，不能操作')
      }
      this.examineDialog = {
        ...this.examineDialog,
        show: true
      }
    },
    async handleExamine(v, msg, cb) {
      const file = this.getActiveItem()
      try {
        let ids = []
        let queryData = {}
        if(!this.allSize) {
          ids = file instanceof Array ? file.map(i => i.id) : [file.id]
        } else {
          queryData = {
            ...this.search,
            total: this.page.total,
            allSize: this.allSize
          }
          if(this.activeName === 'first') {
            queryData.folderId = this.folderId
          } else {
            queryData.tagId = this.tagIds
            delete queryData.ownerUserId
          }
        }
        const res = await MediaApi.auditProgram({
          ...queryData,
          programId: ids,
          auditState: v,
          auditReason: msg,
          folderId: this.folderId
        })
        cb && cb()
        this.allSize = false
        this.$message.success('审核成功')
        this.page.current = 1
        this.fetchList()
      } catch (error) {
        cb && cb(true)
        console.log('MediaApi.auditProgram---', error)
      }
    },
    _openPreView(file) {
      if (!file) return this.$alert('提示', '请选择节目')
      if (file instanceof Array) return this.$alert('提示', '此操作不支持多选')
      this.previewDialog = {
        ...this.previewDialog,
        show: true,
        data: file
      }
    },
    _handleFilter(type) {
      // type: 0 待审核 1 已通过 -1 已拒绝
      this.filterAuditState = type
      this.page.current = 1
      this.fetchList()
    },
    _handleRefresh() {
      // 刷新
      this.page.current = 1
      this.fetchList()
      this.$message.success('刷新成功')
    },
    _handleSearch(data) {
      console.log('search', data)
      this.search = {
        ...this.search,
        queryType: data.name,
        queryParam: data.value
      }
      this.page.current = 1
      this.fetchList()
    },
    initTable(config){
      this.initHeadmuneFlag = true
    },
    // 选择所有页
    handleChangeAllSize(val) {
      this.allSize = val
      this.$refs.list.clearSelection();
    }
  }
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';
.mediaTree {
  width: 100%;
  .el-tabs--border-card {
    border: 0 !important;
  }
  ::v-deep .el-tabs--border-card .el-tabs__content {
    padding: 0;
  }
}
.mediaTree {
  // overflow-x: scroll;
  ::v-deep .el-tabs__item {
    padding: 0 !important;
    width: 125px;
    text-align: center;
  }
  ::v-deep .el-tabs__item:last-child {
    border-right: 0 !important;
  }
  // ::v-deep .el-tabs__item.is-active{background: #fff;border-bottom:0 !important;
  //   }
}
// .leftMain >>> .el-tabs__content {
//   padding-left: 0;
//   padding-right: 0;
// }
// .leftMain {
//   ::v-deep .el-tabs__item{padding:0 !important; width:125px; text-align:center;height: 44px !important; line-height: 44px !important;}
//   ::v-deep .el-tabs__item:last-child{border-right:0 !important;}
// }
</style>

<style>
.media-mkshow .rightMain .el-tabs {
  border-bottom: 0;
}
.media-mkshow .rightMain .el-tabs__content {
  padding: 0;
}
</style>